package com.ridaizu.bean;

import java.io.Serializable;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

import com.google.common.base.Strings;
import com.ridaizu.cache.CacheDataBean;
import com.ridaizu.dao.db.DBManager;
import com.ridaizu.lazy.LazyGoodsDataModel;
import com.ridaizu.model.Goods;
import com.ridaizu.model.form.GoodsForm;
import com.ridaizu.model.search.GoodsSearch;
import com.ridaizu.service.impl.GoodsServiceImpl;
import com.ridaizu.util.DateUtil;

@javax.faces.bean.ManagedBean(name = "goodsBean")
@SessionScoped
public class GoodsBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private LazyDataModel<Goods> lazyModel;

    @ManagedProperty("#{cacheDataBean}")
    private CacheDataBean cacheDataBean;

    @ManagedProperty("#{goodsServiceImpl}")
    private GoodsServiceImpl goodsService;

    @ManagedProperty("#{goodsSearch}")
    private GoodsSearch goodsSearch;

    @ManagedProperty("#{goodsForm}")
    private GoodsForm goodsForm;

	public void searchGoodsSync() {
		lazyModel = new LazyGoodsDataModel(goodsSearch);
	}

	public void viewRegisterGoods() throws SQLException {

		setInitValues(null);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 500);

        RequestContext.getCurrentInstance().openDialog("goods", options, null);
    }

	public void viewUpdateGoods(Goods goods) throws SQLException {

		setInitValues(goods);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 520);

        RequestContext.getCurrentInstance().openDialog("goods", options, null);
    }

	private void setInitValues(Goods goods) throws SQLException {
		goodsForm.clearAll();
		setValues(goods);
	}

	private void setValues(Goods goods) {
		if (goods == null) {
			setRegisterValues();
		} else {
			setUpdateValues(goods);
		}
	}

	private void setRegisterValues() {
	}

	private void setUpdateValues(Goods goods) {
		goodsForm.setId(String.valueOf(goods.getId()));
		goodsForm.setName(goods.getName());
		goodsForm.setTaobaoName(goods.getTaobaoName());
		goodsForm.setGoodsCode(goods.getGoodsCode());
		goodsForm.setBarcode(goods.getBarcode());
		goodsForm.setGoodsTypeId(String.valueOf(goods.getGoodsTypeId()));
		goodsForm.setCapacity(goods.getCapacity());
		goodsForm.setWeight(String.valueOf(goods.getWeight()));
		goodsForm.setWholesalePrice(String.valueOf(goods.getWholesalePrice()));
		goodsForm.setPrice(String.valueOf(goods.getPrice()));
		goodsForm.setSalesPrice(String.valueOf(goods.getSalesPrice()));
		goodsForm.setSummary(goods.getSummary());
		goodsForm.setDetail(goods.getDetail());
		goodsForm.setIngredient(goods.getIngredient());
		goodsForm.setEffect(goods.getEffect());
		goodsForm.setSuitAgeId(String.valueOf(goods.getSuitAgeId()));
		goodsForm.setInstructions(goods.getInstructions());
		goodsForm.setPrecautions(goods.getPrecautions());
		goodsForm.setGoodsUrl(goods.getGoodsUrl());
		goodsForm.setPhotoUrl(goods.getPhotoUrl());
		goodsForm.setThumbnailsUrl(goods.getThumbnailsUrl());
		goodsForm.setDelFlg(goods.isDelFlg());
		goodsForm.setRgtOpt(goods.getRgtOpt());
		goodsForm.setRgtDate(new Date(goods.getRgtDate().getTime()));
		goodsForm.setUpdOpt(goods.getUpdOpt());
		goodsForm.setUpdDate(new Date(goods.getUpdDate().getTime()));
	}

	public void registerGoods() {
		Goods goods = getGoods();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = goodsService.insertModel(goods);
			DBManager.commitTransaction();

			cacheDataBean.setGoodsSelectItemList(null);
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
    }

	public void updateGoods() {

		Goods goods = getGoods();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = goodsService.updateModel(goods);
			DBManager.commitTransaction();

			cacheDataBean.setGoodsSelectItemList(null);
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
	}

	public void deleteGoods() {

		Goods selectedGoods = goodsForm.getSelectedGoods() ;

		if (selectedGoods == null || selectedGoods.getId() < 1) {
	        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", "请选择要删除的商品信息。");
	        FacesContext.getCurrentInstance().addMessage(null, message);

	        return ;
		}

		boolean result = false;
		try {
			DBManager.beginTransaction();
			result = goodsService.deleteModel(selectedGoods.getId());
			DBManager.commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		String resultStr = null;
		if (result) {
			cacheDataBean.setGoodsSelectItemList(null);
			resultStr = String.format("商品[%s]删除成功。", selectedGoods.getName());
		} else {
			resultStr = String.format("商品[%s]删除失败。", selectedGoods.getName());
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Goods delete result", resultStr);
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void registerGoodsResult(SelectEvent event) {
		boolean result = (Boolean) event.getObject();

		handleResult(result, "登录");
	}

	public void updateGoodsResult(SelectEvent event) {

		boolean result = (Boolean) event.getObject();

		handleResult(result, "更新");
	}

	private void handleResult(boolean result, String optStr) {

		String resultStr = null;
		if (result) {
			resultStr = String.format("商品信息%s成功。", optStr);
		} else {
			resultStr = String.format("商品信息%s失败。", optStr);;
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", resultStr);

        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	private Goods getGoods() {

		Goods goods = new Goods();

		if (!Strings.isNullOrEmpty(goodsForm.getId())) {
			goods.setId(Integer.valueOf(goodsForm.getId()));
		}

		goods.setName(goodsForm.getName());
		goods.setTaobaoName(goodsForm.getTaobaoName());

		goods.setGoodsCode(goodsForm.getGoodsCode());
		goods.setBarcode(goodsForm.getBarcode());

		if (!Strings.isNullOrEmpty(goodsForm.getGoodsTypeId())) {
			goods.setGoodsTypeId(Integer.valueOf(goodsForm.getGoodsTypeId()));
		}

		goods.setCapacity(goodsForm.getCapacity());

		if (!Strings.isNullOrEmpty(goodsForm.getWeight())) {
			goods.setWeight(Integer.valueOf(goodsForm.getWeight()));
		}

		if (!Strings.isNullOrEmpty(goodsForm.getWholesalePrice())) {
			goods.setWholesalePrice(Double.valueOf(goodsForm.getWholesalePrice()));
		}

		if (!Strings.isNullOrEmpty(goodsForm.getPrice())) {
			goods.setPrice(Double.valueOf(goodsForm.getPrice()));
		}

		if (!Strings.isNullOrEmpty(goodsForm.getSalesPrice())) {
			goods.setSalesPrice(Double.valueOf(goodsForm.getSalesPrice()));
		}

		goods.setSummary(goodsForm.getSummary());
		goods.setDetail(goodsForm.getDetail());
		goods.setIngredient(goodsForm.getIngredient());
		goods.setEffect(goodsForm.getEffect());

		if (!Strings.isNullOrEmpty(goodsForm.getSuitAgeId())) {
			goods.setSuitAgeId(Integer.valueOf(goodsForm.getSuitAgeId()));
		}

		goods.setInstructions(goodsForm.getInstructions());
		goods.setPrecautions(goodsForm.getPrecautions());
		goods.setGoodsUrl(goodsForm.getGoodsUrl());
		goods.setPhotoUrl(goodsForm.getPhotoUrl());
		goods.setThumbnailsUrl(goodsForm.getThumbnailsUrl());

		goods.setDelFlg(goodsForm.isDelFlg());

		Timestamp currentDate = DateUtil.getCurrentDateTime();

		goods.setRgtOpt("Admin");
		goods.setRgtDate(currentDate);
		goods.setUpdOpt("Admin");
		goods.setUpdDate(currentDate);

		return goods;
	}

	public LazyDataModel<Goods> getLazyModel() {
		return lazyModel;
	}

	public void setLazyModel(LazyDataModel<Goods> lazyModel) {
		this.lazyModel = lazyModel;
	}

	public GoodsServiceImpl getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(GoodsServiceImpl goodsService) {
		this.goodsService = goodsService;
	}

	public GoodsSearch getGoodsSearch() {
		return goodsSearch;
	}

	public void setGoodsSearch(GoodsSearch goodsSearch) {
		this.goodsSearch = goodsSearch;
	}

	public GoodsForm getGoodsForm() {
		return goodsForm;
	}

	public void setGoodsForm(GoodsForm goodsForm) {
		this.goodsForm = goodsForm;
	}

	public CacheDataBean getCacheDataBean() {
		return cacheDataBean;
	}

	public void setCacheDataBean(CacheDataBean cacheDataBean) {
		this.cacheDataBean = cacheDataBean;
	}

}